package com.ruige.goreka.controller;

import com.ruige.goreka.config.VersionConfig;
import com.ruige.goreka.pojo.Result;
import com.ruige.goreka.pojo.Service;
import com.ruige.goreka.pojo.StatusCode;
import com.ruige.goreka.service.GorekaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/goreka")
public class GorekaController {

    @Autowired
    private GorekaService gorekaService;

    /**
     * 接收并注册
     * @param service
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Service service) {
        if (service == null) {
            return new Result(false, StatusCode.ERROR, "服务无效,注册失败!");
        }
        gorekaService.add(service);
        return new Result(true, StatusCode.OK, "服务注册成功!");

    }

    /**
     * 查询所有服务
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Service> serviceList = gorekaService.findAll();
        List<Map> data = new ArrayList<>();
        for (Service service : serviceList) {
            Map<String,String> map = new HashMap();
            map.put("ip", service.getIp());
            map.put("service_name", service.getService_name());
            map.put("port", service.getPort());
            map.put("status", service.getStatus());
            map.put("register_time", simpleDateFormat.format(service.getRegister_time()));
            map.put("last_update_time", simpleDateFormat.format(service.getLast_update_time()));
            map.put("type", service.getType());
            data.add(map);
        }
        return new Result(true, StatusCode.OK, "查询成功", data);
    }


    /**
     * 接收心跳并反馈
     * @param service
     * @return
     */
    @PostMapping("/ping")
    public Result pong(@RequestBody Service service) {

        if (service == null) {
            return new Result(false, StatusCode.ERROR, "服务无效,执行失败!");
        }
        //计算执行时间
        long start = System.currentTimeMillis();
        //查找兵判断当前服务是否存在
        String service_name_ping = service.getService_name();
        Service service_result =  gorekaService.findByServiceName(service_name_ping);
        if (service_result == null||"null".equals(service_result.getService_name()) || "".equals(service_result.getService_name())) {
            return new Result(false,StatusCode.ERROR,new Date().toString()+"  INFO:  ping~pong~server contract unsuccessfully!");
        }
        //服务名若相同,这更新服务状态
        if (service.getService_name().equals(service_name_ping)) {
            gorekaService.update(service);
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        return new Result(true,StatusCode.OK,new Date().toString()+"  INFO:  ping~pong~server contract successfully!"+" execution time: "+time+"ms");
    }

    /**
     * 查询图表信息数据
     * @return
     */
    @GetMapping("/charts")
    public Map fintToChart() {
        Map<String, Object> map = new HashMap<>();
        List<Service> serviceList = gorekaService.findAll();
        List servingData = new ArrayList();
        List invalidData = new ArrayList();
        int serving_producer = 0;
        int serving_consumer = 0;
        int abnormal_producer = 0;
        int abnormal_consumer = 0;
        for (int i = 0; i < serviceList.size(); i++) {
            Service service = serviceList.get(i);
            if ("serving".equals(service.getStatus())) {
                if ("producer".equals(service.getType())) {
                    serving_producer++;
                }
                if ("consumer".equals(service.getType())) {
                    serving_consumer++;
                }
            }
            if ("abnormal".equals(service.getStatus())) {
                if ("producer".equals(service.getType())) {
                    abnormal_producer++;
                }
                if ("consumer".equals(service.getType())) {
                    abnormal_consumer++;

                }
            }
        }
        servingData.add(serving_producer);
        servingData.add(serving_consumer);
        invalidData.add(abnormal_producer);
        invalidData.add(abnormal_consumer);
        map.put("serving", servingData);
        map.put("abnormal", invalidData);
        return map;
    }


    /**
     * 获取当前状态信息
     * @return
     */
    @GetMapping("/status")
    public Map getStatus() {

        List<Service> serviceList = gorekaService.findAll();
        int i = 0;
        for (Service service : serviceList) {
            if ("abnormal".equals(service.getStatus())) {
                i++;
            }
        }
        Map<String, Object> status = new HashMap<>();
        if (i == 0) {
            status.put("status", "完美");
        } else {
            status.put("status", "良好");
        }

        Calendar calendar = Calendar.getInstance();
        status.put("year", calendar.get(Calendar.YEAR));
        status.put("month",calendar.get(Calendar.MONTH)+1);
        status.put("day",calendar.get(Calendar.DAY_OF_MONTH));
        status.put("time",calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE));
        return status;
    }


    @GetMapping("/version")
    public Map<String,String> versionConfig() {
        Map<String, String> map = new HashMap<>();
        VersionConfig versionConfig = gorekaService.getVersion();
        map.put("author", versionConfig.author);
        map.put("version", versionConfig.version);
        map.put("model", versionConfig.model);
        map.put("publicationDate", versionConfig.publicationDate);
        map.put("company", versionConfig.company);
        map.put("telephone", versionConfig.telephone);
        return map;
    }

}
